package com.example.mygis.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.mygis.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.util.StringUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AmapUtil {

    public static final String KEY = "3fb7d7b51e85972f437e23d4a56f7f2d";
//    public static final String URL = "https://restapi.amap.com/v3/geocode/geo?keywords=";
    public static final String URL = "https://restapi.amap.com/v3/place/text?keywords=";


    public static String getLngAndLag(QyNdxx ndxx) throws UnsupportedEncodingException {
        String qymc = ndxx.getAddress().trim();
//        if(!qymc.contains("宁波市")){
//            qymc = "宁波市"+qymc;
//        }
//        String qymc = ndxx.getAddress().trim();
//        if(qymc.contains("号")){
//            qymc = qymc.split("号")[0].toString() + '号';
//        }
        String url = URL + URLEncoder.encode(qymc, "utf-8") + "&output=JSON&key=" + KEY+"&city=宁波市"
                +"&citylimit=true&offset=1";

        try {
            java.net.URL url2 = new URL(url);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            JSONObject a = JSON.parseObject(sb.toString());
            JSONArray sddressArr = JSON.parseArray(a.get("pois").toString());
            if(CollectionUtil.isEmpty(sddressArr)){
                log.error("未查到改企业地址：{}",sddressArr.toString());
                return null;
            }
            JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
            String location = c.get("location").toString();
            String formatted_address = c.get("address").toString();
            ndxx.setAddress(formatted_address);
            return location;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static String getLngAndLagServiceSite(ServiceSite ndxx) throws UnsupportedEncodingException {
        String qymc = ndxx.getAddress().trim();
//        if(!qymc.contains("宁波市")){
//            qymc = "宁波市"+qymc;
//        }
//        String qymc = ndxx.getAddress().trim();
//        if(qymc.contains("号")){
//            qymc = qymc.split("号")[0].toString() + '号';
//        }
        String url = URL + URLEncoder.encode(qymc, "utf-8") + "&output=JSON&key=" + KEY+"&city=宁波市"
                +"&citylimit=true&offset=1";

        try {
            java.net.URL url2 = new URL(url);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            JSONObject a = JSON.parseObject(sb.toString());
            JSONArray sddressArr = JSON.parseArray(a.get("pois").toString());
            if(CollectionUtil.isEmpty(sddressArr)){
                log.error("未查到改企业地址：{}",sddressArr.toString());
                return null;
            }
            JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
            String location = c.get("location").toString();
            String formatted_address = c.get("address").toString();
//            ndxx.setAddress(formatted_address);
            return location;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static String getLngAndLagByName(QyNdxx ndxx,String name) throws UnsupportedEncodingException {
        String url = URL + URLEncoder.encode(name, "utf-8") + "&output=JSON&key=" + KEY+"&city=宁波市"
                +"&citylimit=true&offset=1";
        try {
            java.net.URL url2 = new URL(url);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            JSONObject a = JSON.parseObject(sb.toString());
            JSONArray sddressArr = JSON.parseArray(a.get("pois").toString());
            JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
            String location = c.get("location").toString();
            String formatted_address = c.get("address").toString();
            ndxx.setAddress(formatted_address);
            return location;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static String getCxzyLngAndLag(QyCxzyMd ndxx) throws UnsupportedEncodingException {
        String qymc = ndxx.getQymc().trim();
        String url = URL + URLEncoder.encode(qymc, "utf-8") + "&output=JSON&key=" + KEY+"&city=宁波市"
                +"&citylimit=true&offset=1";

        try {
            java.net.URL url2 = new URL(url);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            JSONObject a = JSON.parseObject(sb.toString());
            JSONArray sddressArr = JSON.parseArray(a.get("pois").toString());
            if(CollectionUtil.isEmpty(sddressArr)){
                return null;
            }
            JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
            String location = c.get("location").toString();
            String formatted_address = c.get("address").toString();
            return location;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static String getCxzyLngAndLag(BlTzxm tzxm) throws UnsupportedEncodingException {
        String name = tzxm.getAddress();
        if(Strings.isBlank(name)){
            name = tzxm.getQymc();
        }
        String url = URL + URLEncoder.encode(name.trim(), "utf-8") + "&output=JSON&key=" + KEY+"&city=宁波市"
                +"&citylimit=true&offset=1";

        try {
            java.net.URL url2 = new URL(url);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            JSONObject a = JSON.parseObject(sb.toString());
            JSONArray sddressArr = JSON.parseArray(a.get("pois").toString());
            if(CollectionUtil.isEmpty(sddressArr)){
                return null;
            }
            JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
            String location = c.get("location").toString();
            String formatted_address = c.get("address").toString();
            if(Strings.isEmpty(tzxm.getAddress())){
                tzxm.setAddress(formatted_address);
            }
            return location;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     *
     * @param xwyq 小微园区
     * @param queryName 查询名称
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getXwyLngAndLag(QyXwyq xwyq,String queryName) throws UnsupportedEncodingException {
        String name = queryName.trim();
        String url = URL + URLEncoder.encode(name, "utf-8") + "&output=JSON&key=" + KEY+"&city=330203"
                +"&citylimit=true&offset=1";

        try {
            java.net.URL url2 = new URL(url);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            JSONObject a = JSON.parseObject(sb.toString());
            JSONArray sddressArr = JSON.parseArray(a.get("pois").toString());
            if(CollectionUtil.isEmpty(sddressArr)){
                String xwyLngAndLag = getXwyLngAndLag(xwyq, xwyq.getAddress());
                if(StringUtil.isEmpty(xwyLngAndLag)){
                    return null;
                }else{
                    return xwyLngAndLag;
                }
            }
            JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
            String location = c.get("location").toString();
            String address = c.get("address").toString();
//            xwyq.setAddress(address);
            return location;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
    /**
     *
     * @param xwyq 村工改
     * @param queryName 查询名称
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getCggLngAndLag(QyCgg xwyq, String queryName) throws UnsupportedEncodingException {
        if(StringUtil.isEmpty(queryName)){
            return null;
        }
        String name = queryName.trim();
        String url = URL + URLEncoder.encode(name, "utf-8") + "&output=JSON&key=" + KEY+"&city=330203"
                +"&citylimit=true&offset=1";

        try {
            java.net.URL url2 = new URL(url);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            JSONObject a = JSON.parseObject(sb.toString());
            JSONArray sddressArr = JSON.parseArray(a.get("pois").toString());
            if(CollectionUtil.isEmpty(sddressArr)){
                String xwyLngAndLag = getCggLngAndLag(xwyq, xwyq.getAddress());
                if(StringUtil.isEmpty(xwyLngAndLag)){
                    return null;
                }else{
                    return xwyLngAndLag;
                }
            }
            JSONObject c = JSON.parseObject(sddressArr.get(0).toString());
            String location = c.get("location").toString();
            String address = c.get("address").toString();
            return location;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    private static double PI = 3.14159265358979324;
    public static double[] gcj02ToWgs(double lng, double lat) {
        double a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
        double ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
        double lat1 = +lat;
        double lng1 = +lng;
        double dlat = transformLat(lng1 - 105.0, lat1 - 35.0);
        double dlng = transformLon(lng1 - 105.0, lat1 - 35.0);
        double radlat = lat1 / 180.0 * PI;
        double magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        double sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
        double mglat = lat1 + dlat;
        double mglng = lng1 + dlng;
        double [] latlng = new double[2];
        latlng[0] = lng1 * 2 - mglng;
        latlng[1] = lat1 * 2 - mglat;
        return latlng;
    }

    public static double transformLat (double x, double y) {
        double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    public static double transformLon (double x, double y) {
        double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
    }

    public final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    /**
     * 高德坐标转百度坐标
     *
     * @param gd_lon 经度
     * @param gd_lat 纬度
     * @return
     */
    public static Map<String, String> gd2bd(String gd_lon, String gd_lat) {
        double longitude = Double.parseDouble(gd_lon);
        double latitude = Double.parseDouble(gd_lat);
        Map<String, String> data = new HashMap<>();
        double x = longitude, y = latitude;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double bd_lon = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        data.put("lon", String.valueOf(bd_lon));
        data.put("lat", String.valueOf(bd_lat));
        return data;
    }


    /**
     * 百度坐标转换高德坐标
     *
     * @param bd_lon 经度
     * @param bd_lat 纬度
     * @return
     */
    public static Map<String, String> bd2gd(String bd_lon, String bd_lat) {
        double longitude = Double.parseDouble(bd_lon);
        double latitude = Double.parseDouble(bd_lat);
        double x = longitude - 0.0065, y = latitude - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        double gd_lon = z * Math.cos(theta);
        double gd_lat = z * Math.sin(theta);
        Map<String, String> data = new HashMap<>();
        data.put("lon", new BigDecimal(gd_lon).setScale(6, RoundingMode.FLOOR).toString());
        data.put("lat", new BigDecimal(gd_lat).setScale(6, RoundingMode.FLOOR).toString());
        return data;
    }


    public static void main(String[] args) {
        try {
            getLngAndLag(null);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
